package com.cwh.springbootMybatis.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cwh.springbootMybatis.bean.DoBiz;
import com.cwh.springbootMybatis.bean.Oamanage;
import com.cwh.springbootMybatis.mapper.DoBizMapper;
import com.cwh.springbootMybatis.mapper.OamanageMapper;
import com.cwh.springbootMybatis.service.OAService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName OAServiceImpl
 * @Description TODO
 * @Author zhengchenggong
 * @Date 2020/4/30 3:50 下午
 * @Version 1.0
 **/
@Service
@Transactional
public class OAServiceImpl implements OAService {

    @Autowired
    OamanageMapper oamanageMapper;

    @Autowired
    DoBizMapper doBizMapper;

    private static final String SUCCESS = "1";
    private static final String FAIL = "0";

    @Override
    public JSONObject getAccessToken(HttpServletRequest request) {

        System.out.println("--------------返回token----------");
        String resysCode = request.getParameter("resysCode");
        String sysPassword = request.getParameter("sysPassword");
        System.out.println("resysCode===" + resysCode);
        System.out.println("sysPassword===" + sysPassword);
        JSONObject jsonObject = new JSONObject();

       /* //返回模式 0-一直成功；1-一直失败；2-先成功后失败；3-先失败后成功 ;4-自定义成功失败（token无法自定义，因为入参没有单据信息）
        Oamanage oamanage = getOamanage();
        String returnmode = oamanage.getReturnmode();
        switch (Integer.valueOf(returnmode)) {
            case 0:
            case 3:
                jsonObject.put("flag", "1");//成功
                jsonObject.put("token", UUID.randomUUID().toString().replaceAll("-", ""));
                break;
            case 1:
                jsonObject.put("flag", "");//失败
                jsonObject.put("msg", "获取token失败");
                break;
            case 2:
                int num = new Random().nextInt(2);
                if (num==0) {
                    jsonObject.put("flag", "1");//成功
                    jsonObject.put("token", UUID.randomUUID().toString().replaceAll("-", ""));
                } else {
                    jsonObject.put("flag", "0");//失败
                }
                break;
        }*/

        jsonObject.put("flag", "1");//成功
        jsonObject.put("token", UUID.randomUUID().toString().replaceAll("-", ""));
        return jsonObject;
    }

    @Override
    public JSONObject doBiz(HttpServletRequest request) {

        System.out.println("-----------财社报送OA接口----------");
        String billid = request.getParameter("billid");
        String billNo = request.getParameter("billNo");
        String billType = request.getParameter("billType");
        String distCode = request.getParameter("distCode");
        String token = request.getParameter("token");
        String fileAddress = request.getParameter("fileAddress");
        String url = fileAddress.substring(0, fileAddress.indexOf("/NXOA/fileDownload"));
//        request.getParameter("auditResult");
//        request.getParameter("auditOpinion");
//        request.getParameter("auditDate");
        JSONObject jsonObject = new JSONObject();
        Oamanage oamanage = getOamanage();
        String returnmode = oamanage.getReturnmode();
        DoBiz doBiz = new DoBiz();
        doBiz.setBillid(billid);
        doBiz.setBillno(billNo);
        doBiz.setBilltype(billType);
        doBiz.setDistcode(distCode);
        doBiz.setToken(token);
        doBiz.setReserve1(url);
        doBiz.setReserve3("0");//未送财社
        //返回模式 0-一直成功；1-一直失败；2-随机模式 ;3-自定义成功失败
        switch (Integer.valueOf(returnmode)) {
            case 0:
                System.out.println("一直成功模式");
                doBizMapper.insertSelective(doBiz);
                jsonObject.put("flag", SUCCESS);//成功
                break;
            case 1:
                System.out.println("一直失败模式");
                jsonObject.put("flag", FAIL);//失败
                break;
            case 2:
                System.out.println("随机模式");
                int num = new Random().nextInt(2);
                if (num==0) {
                    doBizMapper.insertSelective(doBiz);
                    jsonObject.put("flag", SUCCESS);//成功
                } else {
                    jsonObject.put("flag", FAIL);//失败
                }
                break;
            case 3:
                System.out.println("自定义模式");
                String reserve1 = oamanage.getReserve1();
                String reserve2 = oamanage.getReserve2();
                if (reserve1 != null && !"".equals(reserve1)) {
                    String[] split = reserve1.split(",");
                    if (Arrays.asList(split).contains(billid)) {//要成功的集合
                        doBizMapper.insertSelective(doBiz);
                        jsonObject.put("flag", SUCCESS);//成功
                    } else {
                        jsonObject.put("flag", FAIL);//失败
                    }
                }
                if (reserve2 != null && !"".equals(reserve2)) {
                    String[] split2 = reserve2.split(",");
                    if (Arrays.asList(split2).contains(billid)) {//要失败的集合
                        jsonObject.put("flag", FAIL);//失败
                    } else {
                        doBizMapper.insertSelective(doBiz);
                        jsonObject.put("flag", SUCCESS);//成功
                    }
                }
                if ((reserve1 == null || "".equals(reserve1)) && (reserve2 == null || "".equals(reserve2))) {
                    doBiz.setBillid(billid);
                    doBiz.setBillno(billNo);
                    doBiz.setBilltype(billType);
                    doBiz.setDistcode(distCode);
                    doBiz.setToken(token);
                    doBizMapper.insertSelective(doBiz);
                    jsonObject.put("flag", SUCCESS);//成功
                }
                break;
        }
        return jsonObject;
    }

    @Override
    public void doAudit(HttpServletRequest request) {
        String token = request.getParameter("token");
        DoBiz doBiz = doBizMapper.selectByPrimaryKey(token);
        if (doBiz == null) {
            System.out.println("doBiz查询为空,token=" + token);
            return;
        }
        String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        StringBuffer res = new StringBuffer("");
        res.append(doBiz.getReserve1() == null ? "http://127.0.0.1:8080" : doBiz.getReserve1()).append("/nxOaAudit/doAudit?");
        res.append("billid=").append(doBiz.getBillid()).append("&billNo=").append(doBiz.getBillno()).append("&auditResult=")
                .append(doBiz.getReserve2() == null ? "00" : doBiz.getReserve2()).append("&auditOpinion=").append("&auditDate=").append(date)
                .append("&distCode=").append(doBiz.getDistcode()).append("&billtype=").append(doBiz.getBilltype()).append("&text=中宁财社拨款[2020]100号");

        System.out.println("开始报送财社社保");
        System.out.println(res.toString());
        RestTemplate restTemplate = new RestTemplate();
//        Map dto = restTemplate.getForObject(res.toString() , Map.class);
//        Map dto = restTemplate.getForObject("http://127.0.0.1:9999/apis/v1/rest/oaTokensx/test?aa=fffdfd", Map.class);
        Map dto = restTemplate.getForObject(res.toString(), Map.class);
        DoBiz doBiz1 = new DoBiz();
        doBiz1.setToken(doBiz.getToken());
        doBiz1.setReserve3("1");
        doBizMapper.updateByPrimaryKeySelective(doBiz1);
        System.out.println("报送财社社保完成");
        System.out.println(dto);
    }

    @Override
    public void doAudit() {
        Oamanage oamanage = getOamanage();
        String auditflag = oamanage.getAuditflag();
        if (!"true".equals(auditflag)) {
            System.out.println("auditflag==" + auditflag + " 定时任务已关闭");
            return;
        }
        System.out.println("auditflag==" + auditflag + " 定时任务已开启");
        //查询未送财社的
        List<DoBiz> doBizs = doBizMapper.selectByReserve3("0");
        if (doBizs.isEmpty()) {
            System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            System.out.println("任务池为空。。。");
            return;
        }
        System.out.println("任务池共有" + doBizs.size() + "条任务");
        for (DoBiz doBiz : doBizs) {
            String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            StringBuffer res = new StringBuffer("");
            res.append(doBiz.getReserve1() == null || "".equals(doBiz.getReserve1()) ? "127.0.0.1" : doBiz.getReserve1()).append("/nxOaAudit/doAudit?").
                    append("billid=").append(doBiz.getBillid()).append("&billNo=").append(doBiz.getBillno()).append("&auditResult=")
                    .append(doBiz.getReserve2() == null ? "00" : doBiz.getReserve2()).append("&auditOpinion=").append("&auditDate=").append(date)
                    .append("&distCode=").append(doBiz.getDistcode()).append("&billType=").append(doBiz.getBilltype()).append("&text=中宁财社拨款[2020]100号");

            System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            System.out.println("开始报送财社社保 token==" + doBiz.getToken());
            System.out.println("报文信息：" + res.toString());
            RestTemplate restTemplate = new RestTemplate();
            Map dto = restTemplate.getForObject(res.toString(), Map.class);
            if(!"1".equals(dto.get("flag"))){
                System.out.println("失败，提示信息："+dto.get("msg")+" token==" + doBiz.getToken());
                return;
            }
            DoBiz doBiz1 = new DoBiz();
            doBiz1.setToken(doBiz.getToken());
            doBiz1.setReserve3("1");
            doBizMapper.updateByPrimaryKeySelective(doBiz1);
            System.out.println("报送财社社保完成 token==" + doBiz.getToken());
            System.out.println(dto);
        }

    }

    private Oamanage getOamanage() {
        List<Oamanage> oamanages = oamanageMapper.selectActive();
        if (oamanages == null || oamanages.size() != 1) {
            System.out.println("取配置管理表失败，数据有误");
            throw new RuntimeException("取配置管理表失败，数据有误");
        }
        return oamanages.get(0);
    }

    private String getRemortIP(HttpServletRequest request) {
        if (request.getHeader("x-forwarded-for") == null) {
            return request.getRemoteAddr();
        }
        return request.getHeader("x-forwarded-for");
    }

    /**
     * 获取客户端源端口
     * @param request
     * @return
     */
    private Long getRemotePort(HttpServletRequest request){
        try{
            String port = request.getHeader("remote-port");
            if(port!=null&&!"".equals(port)) {
                try{
                    return Long.parseLong(port);
                }catch(NumberFormatException ex){
                    System.out.println("convert port to long error , port:	"+port);
                    return 0L;
                }
            }else{
                return 0L;
            }
        }catch(Exception e){
            System.out.println("get romote port error,error message:"+e.getMessage());
            return 0L;
        }
    }



}
